<?php
/**
 * Created by PhpStorm.
 * User: WuDun 123677924@qq.com
 * Date: 2019/5/30
 * Time: 16:38
 */

namespace api\api\controller;

use cmf\controller\RestBaseController;
use think\facade\Env;
use think\Db;
use api\api\service\IndexService;

class WxpayController extends RestBaseController
{


    /*
     * 积分商城微信支付加密字符串获取
     * app支付生成预支付码方法封装  dunge
     */
    public function getOrderId($body_content, $order_sn)
    {
        //判断是否是登录的用户调用的本接口
        $this->getUserId();
        $total_fee = Db::name('order')->where(array('order_number' => $order_sn))->value('real_amount');
        $param = ['body_content' => $body_content, 'order_sn' => $order_sn, 'notify_url' => 'http://jianguang.sdgoufang.com/api/home/wxpay/notify_url', 'amount' => $total_fee];
        $result = hook_one("app_get_order_id", $param);

        if ($result !== false && !empty($result['error'])) {
            $this->error($result['message']);
        }
        $this->success('支付秘需参数创建成功', $result['data']);
    }

    /*
 * 充值微信支付加密字符串获取
 * app支付生成预支付码方法封装  dunge
 */
    public function getpaystring($body_content, $order_sn)
    {
        //判断是否是登录的用户调用的本接口
        // $userid = $this->getUserId();
        // $where['user_id'] = $userid;
        // $where['out_trade_no'] = $order_sn;
		$total_fee = Db::name('order')->where(array('order_number' => $order_sn))->value('real_amount');
        $param = [
            'body_content' => $body_content,
            'order_sn' => $order_sn,
            'notify_url' => 'http://jianguang.sdgoufang.com/api/api/wxpay/notify_url',
            'amount' => 0.01
        ];

		// $this->logResult("支付数据post==" . json_encode($param));
        $result = hook_one("app_get_order_id", $param);
        if ($result !== false && !empty($result['error'])) {
            $this->error($result['message']);
        }
        $this->success('支付秘需参数创建成功', $result['data']);
    }

    /*
     * 积分商城支付成功回调
     * 支付成功回调接口  dungege
     */
    public function notify_url()
    {

        //引入入口，加载配置
        include Env::get('root_path') . "public/plugins/we_chat/include.php";
        $config = Db::name('plugin')->where('name', 'WeChat')->value('config');
        if (!empty($config) && $config != "null") {
            $config = json_decode($config, true);
            // 3. 创建接口实例
            $wechat = new \WeChat\Pay($config);
            // 4. 获取通知参数
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 去更新下原订单的支付状态
                $out_trade_no = $data['out_trade_no'];
                $total_fee2 = $data['total_fee'];
                $type = substr($out_trade_no, 0, 1);

                    $where['order_number'] = $out_trade_no;
					$result = Db::name('order')->where($where)->where(array('pay_status' => 0))->find();
                    if (!empty($result)) {
                        $userid = $result['user_id'];
                        $fee = intval($total_fee2);
                        $amount = $fee / 100;
                        //开启事务
                        Db::startTrans();
                        //支付完成逻辑
						$data_pay['pay_status'] = 1;
	                    $data_pay['pay_method'] = 2;
                        //更新订单表支付数据和状态
                        $ret_pay = Db::name('order')->where($where)->update($data_pay);
						
						$remark_msg = '支付订单'.$out_trade_no.$amount.'元';
						$balanceLog = userbalanceLog($userid, 2, 2, $amount, '', $remark_msg, $result['order_id'], '');
						//如果订单司机以送达  则代表完成 zjf
                        if($result['status'] == 4 ){
                           Db::name('order')->where($where)->update(array('status'=>5,'finish_time'=>time()));
                            fenrun($result['order_id']);
                        }
						if($result['status'] > 1 ){
							//消息推送
							$indexService = new IndexService();
							$refund_ = $indexService->jpush_send_user(1,'支付完成,订单(' . $out_trade_no . ')已支付',$userid);
						}
                        if (!$ret_pay || !$balanceLog) {
							Db::rollback();
							//记录异常到log.txt文件
							$this->logResult('订单' . $out_trade_no . '支付宝支付成功,但本系统状态未更新，请联系客服处理');
						}
						//派单
						order_auto_designate($result['order_id']);
                        Db::commit();
                        //处理完成之后，告诉微信成功结果！
                        ob_clean();
                        echo $wechat->getNotifySuccessReply();
                    } else {
                        $this->logResult('error');
                        echo 'error';
                    }


            }

        } else {
            echo 'error';
        }

    }


    /**
     * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
     * 注意：服务器需要开通fopen配置
     * @param $word 要写入日志里的文本内容 默认值：空值
     */
    public function logResult($word = '')
    {
        if (!is_dir("paylog/" . date('YmdH'))) {
            mkdir("paylog/" . date('YmdH'), "0777", true);
        } else {
        }
        return file_put_contents("paylog/" . date('YmdH') . "/log.txt", "执行时间：" . date("Y-m-d H:i:s") . $word . "-----华丽的分割线------", FILE_APPEND);

    }

	/*
	 * app支付生成退款方法封装  dunge
	 */
	public function setOrderrefund($order_sn)
	{
	    //判断是否是登录的用户调用的本接口
	    $userid = $this->getUserId();;
		if (!$order_sn){
			$this->error("参数为空");
		}
		
		$indexService = new IndexService();
		$order_obj_ = $indexService->get_order_obj($order_sn,$userid,'user_id');
		
		$result = '';
		$status     = $order_obj_['status'];
		$order_id   = $order_obj_['order_id'];
		$pay_status = $order_obj_['pay_status'];
		$total_fee = $order_obj_['real_amount'];
		$remark_msg = '您取消了订单(' . $order_sn . '),已退款'.$total_fee.'元到微信';
		
		if (!$order_obj_){
			$this->error("订单号有误");
			}
		if ($status > 2){
			$this->error("订单状态有误");
			}
//			Db::startTrans(); //开启事务
			$data_pay['pay_status'] = 2;
	        $data_pay['status']     = 6;
			$update_ = $indexService->update_order_obj_array($order_id,$data_pay);
			//取消日志
			$msg_ret = create_user_message(1,$userid, '取消订单', $remark_msg, $remark_msg);
			if($pay_status == 1){
				
				$order_sn_t = 'T' . substr($order_sn, 1);
				$param = [
					'out_trade_no' => $order_sn,     //系统内部订单号
					'out_refund_no' => $order_sn_t,  //内部的退款单号
					'total_fee' => 0.01,     //订单总金额
					'refund_fee' => 0.01    //退款总金额
				];
				$result = hook_one('create_refund', $param);
		
				// $param = ['out_trade_no' => $order_sn, 'total_amount' => 0.01];
				// $result = hook_one("alipay_order_refund", $param);
				if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
//					Db::rollback();
					$this->error("订单取消失败");
				}
			}
			if($status > 0){//是否已接单
				$up_cancle_ = $indexService->up_user_param($userid,'cancle_num',1);
				//司机消息推送
				$refund_ = $indexService->jpush_send_driver(2,'订单取消，单号(' . $order_sn . ')用户已取消',$order_obj_['driver_id']);
			}
			//消息推送
			$refund_ = $indexService->jpush_send_user(1,'您的订单(' . $order_sn . ')取消成功',$userid);
			if(!$update_ ){
//				Db::rollback();
				$this->error("订单取消失败");
			}
			// 提交事务
//			Db::commit();
			$this->success('支付宝退款成功', $result);
	}
}